﻿using System;
using System.Collections.Generic;
using System.Linq;
using ExpertSystem.Interfaces;

namespace ExpertSystem.Domains
{
    [Serializable]
    public class AsyncRuleset:Ruleset
    {
        public event EventHandler Castomize;
        public event EventHandler RuleActive;

        public AsyncRuleset(string name):base(name,true)
        {
        }

        public override void ActivateRule(object o, EventArgs eventArgs)
        {
            RuleActive(o, eventArgs);
        }

        private void AsyncResolveVariable(IVariable variable, List<IRule> rules)
        {
            var en = rules.GetEnumerator();
            en.MoveNext();
            if (en.Current == null)
            {
                return;
            }
            while (!variable.HaveValue())
            {
                if (en.Current.CanBeAvtivated())
                {
                    if (en.Current.CanBeResolved())
                    {
                        en.Current.Resolve();
                        en.MoveNext();
                    }
                    else
                    {
                        if (!_stack.Contains(en.Current.CanNotBeResolvedVariable()))
                            _stack.Push(en.Current.CanNotBeResolvedVariable());
                        AsyncResolveVariable(en.Current.CanNotBeResolvedVariable(), _rules.Where(x => x.IsReternedValueEquals(en.Current.CanNotBeResolvedVariable()) && !x.IsActivated() && x.CanBeAvtivated()).ToList());
                        if (!_stack.Peek().HaveValue())
                        {
                            en.MoveNext();
                        }
                    }
                }
                else
                {
                    en.MoveNext();
                }

            }

        }

        public override void CastomizeView(object o, EventArgs eventArgs)
        {
            Castomize(o,eventArgs);
        }

    }
}
